#include "stdafx.h"
#include "Reflection.h"
#include "Globals.h"
#include "Constant.h"

void Reflection::Init(char *szFileNFG, GLuint *textureID)
{
	m_Texture = new cObjectTexture();
	m_Texture->m_uiaTextureID = textureID;

	m_Model = new cObjectModel();
	m_Model->Init(szFileNFG);

	//Create Reflection Shader
	m_Shader = ReflectionShader();
	m_Shader.Init("../Resources/Shaders/ReflectionShaderVS.vs","../Resources/Shaders/ReflectionShaderFS.fs");
}

void Reflection::Draw(ESContext *esContext)
{
	glUseProgram(m_Shader.program);
	glBindBuffer(GL_ARRAY_BUFFER, m_Model->GetVertexID());
	int size;
	glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
	size /= sizeof(Vertex);
	if(m_Shader.VertPosition != -1)
	{
		glEnableVertexAttribArray(m_Shader.VertPosition);
		glVertexAttribPointer(m_Shader.VertPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if(m_Shader.VertNorm != -1)
	{
		glEnableVertexAttribArray(m_Shader.VertNorm);
		glVertexAttribPointer(m_Shader.VertNorm, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3) + sizeof(Vector2));
	}

	//Bind Matrix
	if(m_Shader.WVPMatrix != -1)
	{
		Matrix maView = Globals::MainCamera->GetVPMatrix();
		glUniformMatrix4fv(m_Shader.WVPMatrix, 1, GL_FALSE, (GLfloat*)&(m_maLocalW * maView).m[0][0]);
	}
	if(m_Shader.WMatrix != -1)
	{
		glUniformMatrix4fv(m_Shader.WMatrix, 1, GL_FALSE, (GLfloat*)&m_maLocalW.m[0][0]);
	}

	//Bind Camera Position
	if(m_Shader.CameraPosition != -1)
	{
		Vector3 cameraPosition = Globals::MainCamera->GetPosition();
		glUniform3f(m_Shader.CameraPosition, cameraPosition.x, cameraPosition.y, cameraPosition.z);
	}

	//Bind Texture
	if(m_Shader.Texture != -1)
	{
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_CUBE_MAP, m_Texture->GetTextureID()[0]);
		glUniform1i(m_Shader.Texture, 0);
	}

	//Bind Indices
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Model->GetIndiceID());
	glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
	size /= sizeof(GLuint);
	glDrawElements(GL_TRIANGLES, m_Model->GetIndiceNumber(), GL_UNSIGNED_INT, 0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

Reflection::~Reflection()
{
}